/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import Database.ImportSongs;
import Records.RecordsMain;
import Database.UpdateLibraryImp;
import java.io.File;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Alexander
 */
public class LibraryTable implements Runnable {

    private static String[][] array;
    private volatile boolean running = true;

    public void terminate() {
        System.out.println("LibraryTable.terminate()");
        running = false;
    }

    @Override
    public void run() {
        System.out.println("LibraryTable.run()");
        JFileChooser chooser = new JFileChooser();
        chooser.setApproveButtonText("Import");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = chooser.showSaveDialog(chooser);
        if (result == JFileChooser.APPROVE_OPTION) {
            File f = chooser.getSelectedFile();

            RecordsMain.dba.truncateLibTables();
            RecordsMain.clearFilePathList();
            try {
                RecordsMain.dba.createDirectory();
                RecordsMain.dba.insertLibDirectoryPath(f.getAbsolutePath());
            } catch (SQLException ex) {
                try {
                    RecordsMain.dba.dropDirectory();
                    RecordsMain.dba.createDirectory();
                    RecordsMain.dba.insertLibDirectoryPath(f.getAbsolutePath());
                } catch (SQLException ex1) {
                    Logger.getLogger(LibraryTable.class.getName()).log(Level.SEVERE, null, ex1);
                }
            }

            DefaultTableModel model = (DefaultTableModel) RecordsMain.getUI().userLibrary.getModel();

            while (model.getRowCount() > 0) {
                model.removeRow(0);
            }

            ImportSongs.importSongs(f.getAbsolutePath());
        } else if (result == JFileChooser.CANCEL_OPTION) {
            System.out.println("Cancel was selected...Restarting update...");
            UpdateLibraryImp.updater();
        }
    }

    /**
     * @return the array
     */
    public static String[][] getArray() {
        return array;
    }

    /**
     * @param aArray the array to set
     */
    public static void setArray(String[][] aArray) {
        array = aArray;
    }
}
